package com.freeter.ExcelUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

public class XlsTool {
	
	private Workbook workbook;
	
	
	public XlsTool(File srcFile) {
		super();
		try {
			this.workbook =  new HSSFWorkbook(new FileInputStream(srcFile));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  
	}
	
	public XlsTool(Workbook workbook) {
		super();
		this.workbook = workbook;
		
		
	}


	public Sheet getSheet(int indx){
		
		return workbook.getSheetAt(indx);
	}
	
	/**
	 * 
	* @Title: doGetStringLines4Sheet 
	* @Description: 读取xls文件,将每一行信息, 组合在一起.
	* @param @param sheet
	* @param @param start_row
	* @param @param end_row
	* @param @param start_col
	* @param @param end_col
	* @param @return    设定文件 
	* @return List<String>    返回类型 
	* @throws
	* @author zhou   
	* @date 2015年2月2日 下午5:45:57
	 */
	public  List<String> doGetStringLines4Sheet(Sheet sheet,int start_row,int end_row,int start_col,int end_col){
		
		List<String> xls_data_list=new ArrayList<String>();

		int rows=sheet.getPhysicalNumberOfRows();  
		if(start_row>rows){
			return null;
		}
		
		if(end_row>rows){
			end_row=rows;
		}
		
		for(int indx=start_row;indx<=end_row;indx++){
			
			Row row = sheet.getRow(indx);
			if(row!=null){
				String row_content=parseRow(row,start_col,end_col);
				
				if (row_content.matches(".*[0-9]+.*")) {
					
					xls_data_list.add(row_content);
				}
				
			}
			
		}
		
		return xls_data_list;
		
		
	}

	private String parseRow(Row row, int start_col, int end_col) {
		
		StringBuffer buffer=new StringBuffer();
		
		for(int i=start_col;i<=end_col;i++){
			
			Cell cell = row.getCell(i);
			if(cell!=null){
				cell.setCellType(Cell.CELL_TYPE_STRING);
				buffer.append(cell.getStringCellValue());
				buffer.append(";");
			}
			else{
				buffer.append(";");
			}
			
		}
		
		String ret_str=buffer.toString();
		if(ret_str.endsWith(";")){
			ret_str=ret_str.substring(0, ret_str.length()-1);
		}
		return ret_str;
	}

}
